package dk.peterbn.intervaltrainer;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.*;
import dk.peterbn.intervaltrainer.model.Interval;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: peter
 * Date: 9/2/11
 * Time: 11:05 AM
 * To change this template use File | Settings | File Templates.
 */
public class IntervalTrainer extends Activity implements TextToSpeech.OnInitListener{
    private static final int TTS_DATA_CHECK_CODE = 0x1;
    private TextToSpeech tts;

    private TimerService timerService;
    private boolean serviceBound;
    private List<Interval> intervals;
    private ListView intervalList;
    private TextView viewHead;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Find the list of items
        //todo: Make sure the file exists
        File file = new File("/sdcard/IntervalTrainer/program.pgm");
        intervals = new ArrayList<Interval>();
        try {
            Scanner reader = new Scanner(file);
            while (reader.hasNextLine()) {
                Interval interval = Interval.parse(reader.nextLine());
                if (interval != null) {
                    intervals.add(interval);
                }
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        setContentView(R.layout.main);
        intervalList = (ListView) findViewById(R.id.intervalList);
        intervalList.setAdapter(new ArrayAdapter<Interval>(this, R.layout.listitem, intervals));

        viewHead = (TextView) findViewById(R.id.current_item_view);
        TextView totalTimeView = (TextView) findViewById(R.id.total_time_view);
        int seconds = 0;
        for (Interval interval : intervals) {
            seconds += interval.getSeconds();
        }
        String totalTime = getResources().getString(R.string.total_time_label, seconds / 60, seconds % 60);
        totalTimeView.setText(totalTime);

        doBindService();
        //initialize TTS
        Intent ttsCheckIntent = new Intent();
        ttsCheckIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(ttsCheckIntent, TTS_DATA_CHECK_CODE);
    }


    public void startTimer(View button) {
        timerService.startTimer(intervals);
    }

    public void stopTimer(View button) {
        timerService.stopTimer();
    }

    public void skipTimer(View button) {
        timerService.skipForward();
    }

    private void doBindService() {
        if (!serviceBound) {
            Intent serviceIntent = new Intent(this, TimerService.class);
            bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
            serviceBound = true;
        }
    }

    private void doUnbindService() {
        if (serviceBound) {
            unbindService(serviceConnection);
            serviceBound = false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TTS_DATA_CHECK_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                // success, create the TTS instance
                tts = new TextToSpeech(this, this);
            } else {
                // missing data, install it
                Intent installIntent = new Intent();
                installIntent.setAction(
                        TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    }

    public void onInit(int i) {
        tts.setLanguage(Locale.ENGLISH);
        timerService.setTts(tts);
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doUnbindService();
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            timerService = ((TimerService.ServiceBinder) iBinder).getService();
            timerService.setUpdateListCallback(new UpdateListCallback());
        }

        public void onServiceDisconnected(ComponentName componentName) {
            timerService = null;
        }
    };

    public class UpdateListCallback {

        private View previousChild;

        public void setActiveInterval(final Interval activeInterval) {
            runOnUiThread(new Runnable() {
                public void run() {
                    View childAt = intervalList.getChildAt(intervals.indexOf(activeInterval));
                    Log.d("UpdateListCallback", childAt.toString());
                    childAt.setBackgroundResource(R.color.list_active_color);
                    childAt.invalidate();
                    viewHead.setText(activeInterval.toString());
                    viewHead.invalidate();
                    if (previousChild != null) {
                        previousChild.setBackgroundResource(R.color.list_inactive_color);
                        previousChild.invalidate();
                    }
                    previousChild = childAt;
                }
            });
        }
    }
}